﻿@page "/Admin/FolderSelect"
@using JxAudio.Core.Entity
@using Microsoft.Extensions.Localization
@using FreeSql
@using JxAudio.Web.Jobs
@using Longbow.Tasks
@using Serilog

@inject SwalService SwalService

@inject IStringLocalizer<FolderSelect> FolderSelectLocalizer

<AdminTable TItem="DirectoryEntity" ShowToolbar="true" ShowExtendButtons="true" OnSaveAsync="OnSaveAsync"
            ConfirmDeleteContentText="@FolderSelectLocalizer["Delete"]" OnDeleteAsync="OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.Provider" LookupServiceKey="plugin"></TableColumn>
        <TableColumn @bind-Field="@context.Name" Searchable="true"></TableColumn>
        <TableColumn @bind-Field="@context.IsAccessControlled"></TableColumn>
        <TableColumn @bind-Field="@context.UserEntities">
            <Template Context="value">
                @if (value.Value != null)
                {
                    @string.Join(",", value.Value.Select(x => x.UserName))
                }
            </Template>
            <EditTemplate Context="value">
                <div class="col-12 col-sm-6 col-md-6">
                    <MultiSelect @bind-Value="@value.UserList" Items="_userList"></MultiSelect>
                </div>
            </EditTemplate>
        </TableColumn>
        <TableColumn @bind-Field="@context.Path">
            <EditTemplate Context="value">
                <div class="col-12">
                    <label class="form-label is-display">@FolderSelectLocalizer["Content"]</label>
                    @if (value.Id == 0)
                    {
                        <SelectPathComponent ProviderId="value.Provider" @bind-Path="@value.Path"></SelectPathComponent>
                    }
                    else
                    {
                        <Display @bind-Value="@value.Path" ShowLabel="false"></Display>
                    }
                   
                </div>
            </EditTemplate>
        </TableColumn>
    </TableColumns>
</AdminTable>

@code {
    private readonly List<SelectedItem> _userList = UserEntity.Select.ToList(x => new SelectedItem(x.Id.ToString(), x.UserName!));

    private async Task<bool> OnSaveAsync(DirectoryEntity arg1, ItemChangedType arg2)
    {
        await arg1.SaveAsync();
        BaseEntity.Orm.GetRepository<DirectoryEntity>().SaveMany(arg1, nameof(DirectoryEntity.UserEntities));
        //await arg1.SaveManyAsync(nameof(DirectoryEntity.UserEntities));
        var ret = await SwalService.ShowModal(new SwalOption()
        {
            Content = FolderSelectLocalizer["RunScanContent"],
            Category = SwalCategory.Question
        });
        if (ret)
        {
            _ = TaskServicesManager.Get(nameof(ScanJob))!.Run();
        }
        return true;
    }

    private async Task<bool> OnDeleteAsync(IEnumerable<DirectoryEntity> arg)
    {
        using var uow = BaseEntity.Orm.CreateUnitOfWork();
        try
        {
            foreach (var item in arg)
            {
                item.Delete(true);
            }

            var repo = BaseEntity.Orm.GetRepository<TrackEntity>();
            await repo.DeleteCascadeByDatabaseAsync(x => arg.Any(y => y.Id == x.DirectoryId));
            uow.Commit();
            var ret = await SwalService.ShowModal(new SwalOption()
            {
                Content = FolderSelectLocalizer["RunClearContent"],
                Category = SwalCategory.Question
            });
            if (ret)
            {
                TaskServicesManager.GetOrAdd<ClearJob>(TriggerBuilder.Default.Build());
            }
            return true;
        }
        catch (Exception e)
        {
            Log.Error(e, "删除文件夹失败");
            uow.Rollback();
            return false;
        }
    }

}